package com.example.android.sensortest;

import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class LocationActivity extends Activity {
    LocationManager mLocationManager;

    List<String> mLocationProviders;
    List<LocationListener> mLocationListeners = new ArrayList<LocationListener>();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_sensors);

        final LinearLayout container = (LinearLayout) findViewById(R.id.container);

        // Get a handle to the SensorManager
/*
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
*/

        // Get a list of all available location providers. Generally you'd want to use
        // getBestProvider for a given Criteria, and use several providers if your use case
        // calls for it. More information on location strategies can be found in the
        // "Obtaining User Location" part of the developer guide on developer.android.com.
/*
        mLocationProviders = mLocationManager.getAllProviders();
*/

        // You can also use getLastKnownLocation to get a cached location from a provider
        // without spinning it up (although the cached location may be very stale)

        // We'll use this to load a layout template for each location provider
        final LayoutInflater layoutInflater = getLayoutInflater();

        for (String locationProviderName : mLocationProviders) {

            // Inflate the layout template and get handles to the individual views it contains
            LocationProvider locationProvider = mLocationManager.getProvider(locationProviderName);
            final View sensorRootView = layoutInflater
                    .inflate(R.layout.item_location_provider, container, false);
            final TextView titleView = (TextView) sensorRootView.findViewById(R.id.provider_title);
            final TextView metadataView = (TextView) sensorRootView.findViewById(
                    R.id.provider_metadata);
            final TextView valuesView = (TextView) sensorRootView
                    .findViewById(R.id.provider_values);
            final TextView statusView = (TextView) sensorRootView
                    .findViewById(R.id.provider_status);

            // Set the title and metadata
            titleView.setText(locationProvider.getName());

            final StringBuilder sb = new StringBuilder();
/*
            sb.append("Accuracy: " + getProviderAccuracyString(locationProvider.getAccuracy()));
            sb.append("\nPower requirement: " + getPowerRequirementString(
                    locationProvider.getPowerRequirement()));
            sb.append("\nHas monetary cost: " + locationProvider.hasMonetaryCost());
            sb.append("\nRequires cell: " + locationProvider.requiresCell());
            sb.append("\nRequires network: " + locationProvider.requiresNetwork());
            sb.append("\nRequires satellite: " + locationProvider.requiresSatellite());
            sb.append("\nSupports altitude: " + locationProvider.supportsAltitude());
            sb.append("\nSupports bearing: " + locationProvider.supportsBearing());
            sb.append("\nSupports speed: " + locationProvider.supportsSpeed());
*/
            metadataView.setText(sb.toString());

            statusView.setText("Status: N/A");

            // Create a new LocationListener that will update the values and status views
            // for the provider when the provider reports location changes.
            mLocationListeners.add(new LocationListener() {
                public void onLocationChanged(Location location) {
                    sb.setLength(0);

/*
                    sb.append("Latitude: " + location.getLatitude());
                    sb.append("\nLongitude: " + location.getLongitude());
                    if (location.hasAltitude()) {
                        sb.append("\nAltitude: " + location.getAltitude());
                    }
                    if (location.hasBearing()) {
                        sb.append("\nBearing (deg): " + location.getBearing());
                    }
                    if (location.hasSpeed()) {
                        sb.append("\nSpeed (m/s): " + location.getSpeed());
                    }
                    if (location.hasAccuracy()) {
                        sb.append("\nAccuracy (m): " + location.getAccuracy());
                    }
*/

                    valuesView.setText(sb.toString());
                }

                public void onStatusChanged(String provider, int status, Bundle extras) {
                    statusView.setText("Status: " + getProviderStatusString(status));
                }

                public void onProviderEnabled(String provider) {
                    statusView.setText("Status: ENABLED");
                }

                public void onProviderDisabled(String provider) {
                    statusView.setText("Status: DISABLED");
                }
            });

            container.addView(sensorRootView);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Resume is called after onCreate when the activity is first loaded, and after it's
        // put back into the foreground. In our onResume, we'll register our listeners, that
        // we created earlier on in onCreate.

        if (mLocationManager == null) {
            return;
        }

        for (int i = mLocationProviders.size() - 1; i >= 0; i--) {
            // Request location updates as frequently (minTime=0) and as precisely (minDistance=0)
            // as possible. You generally want to use some actual numbers here that make sense
            // for your use case
/*
            mLocationManager.requestLocationUpdates(
                    mLocationProviders.get(i),      // the location provider
                    0,                              // the minimum refresh interval we need (msec)
                    0,                              // the minimum distance change from the
                                                    // previously known location that we care about
                                                    // (in meters)
                    mLocationListeners.get(i));     // the listener
*/
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        // onPause is called when the activity is backgrounded. We'll want to unregister our
        // listeners since we don't care to receive updates while we're not in the foreground.
        // This is especially important for GPS ... we DO NOT want to listen for GPS updates
        // needlessly.

        if (mLocationProviders == null || mLocationListeners == null) {
            return;
        }

        for (int i = mLocationProviders.size() - 1; i >= 0; i--) {
/*
            mLocationManager.removeUpdates(mLocationListeners.get(i));
*/
        }
    }

    private static String getProviderStatusString(int status) {
        switch (status) {
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                return "TEMPORARILY_UNAVAILABLE";
            case LocationProvider.AVAILABLE:
                return "AVAILABLE";
            case LocationProvider.OUT_OF_SERVICE:
                return "OUT_OF_SERVICE";
        }
        return "(Unknown provider accuracy)";
    }

    private static String getProviderAccuracyString(int accuracy) {
        switch (accuracy) {
            case Criteria.ACCURACY_COARSE:
                return "ACCURACY_COARSE";
            case Criteria.ACCURACY_FINE:
                return "ACCURACY_FINE";
        }
        return "(Unknown provider accuracy)";
    }

    private static String getPowerRequirementString(int powerRequirement) {
        switch (powerRequirement) {
            case Criteria.POWER_HIGH:
                return "POWER_HIGH";
            case Criteria.POWER_MEDIUM:
                return "POWER_MEDIUM";
            case Criteria.POWER_LOW:
                return "POWER_LOW";
        }
        return "(Unknown power requirement)";
    }
}
